layui.define(['table', 'form', 'layer', 'aphp', 'laytpl'], function (exports) {
    "use strict";

    var MOD_NAME = 'aphpTable',
        $ = layui.$,
        table = layui.table,
        form = layui.form,
        layer = layui.layer,
        aphp = layui.aphp,
        laytpl = layui.laytpl;

    var init = {
        table_elem: '#currentTable',
        table_render_id: 'currentTable',
    };

    var ColumnsForSearch = [];

    var aphpTable =  {
        // 绑定事件
        bindEvent: function () {
            // 刷新表格
            $(document).on('click', '[data-table-refresh]', function () {
                var tableId = $(this).data('table-refresh');
                if (tableId === undefined || tableId === '' || tableId == null) {
                    tableId = init.table_render_id;
                }
                table.reload(tableId);
            });
            // 刷新页面
            $(document).on('click', '[data-page-refresh]', function () {
                parent.layui.admin.refreshThis();
            });
            // 单行删除
            $(document).on('click', '.layui-tr-del', function() {
                var that = $(this),
                    tableId = $(this).data('table'),
                    href = !that.attr('data-href') ? that.attr('href') : that.attr('data-href');
                tableId = tableId || init.table_render_id;
                aphp.request.getConfirm(href, '确认要删除吗？', 0, function() { table.reload(tableId); });
                return false;
            });
            // 批量操作
            $(document).on('click', '[data-batch-all]', function() {
                var url = $(this).data('href') || window.location.href,
                    title = $(this).data('title') || '进行操作',
                    tableId = $(this).data('batch-all') || init.table_render_id || 'currentTable',
                    sign = $(this).data('sign') || '', //标识
                    confirm = $(this).data('confirm') || false;

                var ids = aphp.getCheckedIds(tableId);
                if (ids === '') {
                    layer.msg('请选择ID', { icon: 3, time: 2000 });
                    return false;
                }
                var post = {ids: ids};
                if (sign === 'enable' || sign === 'disable') {
                    post.param = 'status';
                    post.value = (sign === 'enable') ? 1 : 0;
                }
                var success = function() { table.reload(tableId); };
                if (confirm !== false) {
                    confirm = (typeof confirm === 'string') ? confirm : '确认要' + title + '吗？';
                    aphp.request.postConfirm(url, post, confirm, 0, success);
                } else {
                    aphp.request.post(url, post, 0, success);
                }
                 return false;
            });
            // 请求事件
            $(document).on('click', '[data-request]', function() {
                var url = $(this).data('request') || $(this).attr("href"),
                    title = $(this).data('title') || '进行操作',
                    tableId = $(this).data('table') || init.table_render_id || 'currentTable',
                    checkbox = $(this).data('checkbox') || false,
                    confirm = $(this).data('confirm') || false;

                if (checkbox !== false) {
                    var ids = aphp.getCheckedIds(tableId);
                    if (ids === '') {
                        layer.msg('请选择ID', {icon: 3, time: 1500});
                        return false;
                    }
                    var field = (typeof checkbox === 'string') ? checkbox : 'id';
                    url += (url.indexOf("?") === -1 ? "?" : "&") + field + '=' + ids;
                }
                var success = function() { table.reload(tableId); };
                if (confirm !== false) {
                    confirm = (typeof confirm === 'string') ? confirm : '确认要' + title + '吗？';
                    aphp.request.getConfirm(url, confirm, 0, success);
                } else {
                    aphp.request.get(url, 0,  success);
                }
                return false;
            });
        },
        // 初始化表格
        render: function (options) {
            options.init = options.init || init;
            options.modifyReload = aphp.getParam(options.modifyReload, true);
            options.id = options.id || options.init.table_render_id;
            options.elem = options.elem || options.init.table_elem;
            options.cols = options.cols || [];
            options.layFilter = options.id + '_LayFilter';
            options.url = options.url || options.init.index_url || window.location.href;
            options.response = options.response || {statusCode: 200};
            options.search = aphp.getParam(options.search, true);
            options.showSearch = aphp.getParam(options.showSearch, true);
            options.searchFormVisible = aphp.getParam(options.searchFormVisible, false);
            options.searchFormTpl = aphp.getParam(options.searchFormTpl || options.init.searchFormTpl, false);
            options.defaultToolbar = options.defaultToolbar || ['filter', 'print', 'exports'];
            options.quickSearch = options.quickSearch || '';
            options.cellMinWidth = aphp.getParam(options.cellMinWidth, 80); // 单元格最小宽度
            //options.maxWidth = 0;
            // options.quickSearchTip = options.quickSearchTip || '搜索';
            if (options.search && options.showSearch) {
                options.defaultToolbar.push({
                    title: '搜索',
                    layEvent: 'TABLE_SEARCH',
                    icon: 'layui-icon-search',
                    extend: 'data-table-id="' + options.id + '"'
                })
            }
            options.even = aphp.getParam(options.even, true);
            // 判断是否为移动端
            if (aphp.isMobile()) {
                options.defaultToolbar = !options.search ? ['filter'] : ['filter', {
                    title: '搜索',
                    layEvent: 'TABLE_SEARCH',
                    icon: 'layui-icon-search',
                    extend: 'data-table-id="' + options.id + '"'
                }];
            }
            options.searchInput = options.search ? aphp.getParam(options.searchInput, true) : false;
            var tableDone = options.done || function() {};
            options.done = function(res, curr, count) {
                tableDone(res, curr, count);
            };
            options.cols = aphpTable.colsFormat(options.cols, options.init); // 格式化cols
            $(options.elem).attr('lay-filter', options.layFilter);
            //自定义搜索
            if (options.search === true && options.searchFormTpl !== false) {
                var data = options.tpldata || {}
                laytpl($('#' + options.searchFormTpl).html()).render(data, function (html) {
                    $(options.elem).before(html);
                    aphpTable.listenSearch(options.id); // 监听搜索
                })
                form.render();
            }
            if (options.search === true && options.searchFormTpl === false) {
                aphpTable.renderSearch(options.cols, options.elem, options.id, options.searchFormVisible); // 初始化表格搜索
            } else if (options.quickSearch) {
                aphpTable.listenSearch(options.id); // 监听搜索
            }
            // 初始化顶部工具栏
            options.toolbar = options.toolbar || ['refresh_table', 'add', 'delete', 'export'];
            options.toolbar = aphpTable.topBarRender(options);
            var newTable = table.render(options);
            // 监听表格搜索开关显示
            aphpTable.listenToolbar(options.layFilter, options.id);
            // 监听状态开关切换
            aphpTable.renderSwitch(options.cols, options.init, options.id, options.modifyReload);
            // 监听字段编辑
            aphpTable.listenFieldEdit(options.init, options.layFilter, options.id, options.modifyReload);
            return newTable;
        },
        // 顶部工具栏渲染
        topBarRender: function(options) {
            var d = options.toolbar,
                tableId = options.id,
                searchInput = options.searchInput,
                quickSearch = options.quickSearch || '',
                //quickSearchTip = options.quickSearchTip || '搜索',
                elem = options.elem,
                init = options.init;
            d = d || [];
            var toolbarHtml = '';
            $.each(d, function(i, v) {
                if (v === 'refresh_table') {
                    toolbarHtml += '<button class="layui-btn layui-btn-sm aphp-btn-primary" data-table-refresh="' + tableId + '"><i class="layui-icon layui-icon-refresh"></i> </button>\n';
                } else if (v === 'refresh') {
                    toolbarHtml += '<button class="layui-btn layui-btn-sm aphp-btn-primary" data-page-refresh="' + tableId + '"><i class="layui-icon layui-icon-refresh"></i> </button>\n';
                } else if (v === 'add') {
                    if (aphp.checkAuth('add', elem)) {
                        toolbarHtml += '<button class="layui-btn layui-btn-sm" data-open="' + init.add_url + '" data-title="添加"><i class="layui-icon layui-icon-add-1"></i><span class="layui-hide-xs"> 添加</span></button>\n';
                    }
                } else if (v === 'enable') {
                    if (aphp.checkAuth('modify', elem)) {
                        toolbarHtml += '<button class="layui-btn layui-btn-normal layui-btn-sm" data-href="' + init.modify_url + '" data-batch-all="' + tableId + '" data-sign="enable"><i class="layui-icon layui-icon-eye"></i><span class="layui-hide-xs"> 启用</span></button>\n';
                    }
                } else if (v === 'disable') {
                    if (aphp.checkAuth('modify', elem)) {
                        toolbarHtml += '<button class="layui-btn layui-btn-warm layui-btn-sm" data-href="' + init.modify_url + '" data-batch-all="' + tableId + '" data-sign="disable"><i class="layui-icon layui-icon-eye-invisible"></i><span class="layui-hide-xs"> 停用</span></button>\n';
                    }
                } else if (v === 'delete') {
                    if (aphp.checkAuth('delete', elem)) {
                        toolbarHtml += '<button class="layui-btn layui-btn-sm layui-btn-danger" data-href="' + init.delete_url + '" data-batch-all="' + tableId + '" data-confirm="确定要删除吗？"><i class="layui-icon layui-icon-delete"></i><span class="layui-hide-xs"> 删除</span></button>\n';
                    }
                } else if (typeof v === "object") {
                    $.each(v, function(ii, vv) {
                        vv.class = vv.class || '';
                        vv.icon = vv.icon || '';
                        vv.auth = vv.auth || '';
                        vv.url = vv.url || '';
                        vv.method = vv.method || 'open';
                        vv.title = vv.title || vv.text;
                        vv.text = vv.text || vv.title;
                        vv.extend = vv.extend || '';
                        vv.checkbox = vv.checkbox || false;
                        vv.html = vv.html || '';
                        vv.sign = vv.sign || '';
                        vv.confirm = vv.confirm || '';
                        if (aphp.checkAuth(vv.auth, elem)) {
                            toolbarHtml += aphpTable.topBarBuild(vv, tableId);
                        }
                    });
                }
            });
            if (quickSearch) {
                var quick = quickSearch.split("#");
                if (quick.length < 2) {
                    quick[1] = '搜索';
                }
                toolbarHtml += '<div class="layui-input-inline layui-hide-xs" style="float: right;margin-right: 40px;"><input id="layui-input-search" value="" placeholder="'+quick[1]+'" data-field="'+quick[0]+'" class="layui-input" style="height:30px;"><div class="layui-input-suffix"><i class="layui-icon layui-icon-eye" style="cursor: pointer;"></i></div></div>\n'
            }
            return '<div>' + toolbarHtml + '</div>';
        },
        // 顶部工具栏生成
        topBarBuild: function(toolbar, tableId) {
            tableId = tableId || init.table_render_id || 'currentTable';
            toolbar.html = toolbar.html || '';
            if (toolbar.html !== '') {
                return toolbar.html;
            }
            toolbar.class = toolbar.class || '';
            toolbar.icon = toolbar.icon || '';
            //toolbar.auth = toolbar.auth || '';
            //toolbar.field = toolbar.field || 'id';
            toolbar.url = toolbar.url || '';
            toolbar.extend = toolbar.extend || '';
            toolbar.method = toolbar.method || 'open';
            toolbar.title = toolbar.title || toolbar.text;
            toolbar.text = toolbar.text || toolbar.title;
            toolbar.checkbox = toolbar.checkbox || false;
            toolbar.sign = toolbar.sign || '';
            toolbar.confirm = toolbar.confirm || false;

            var html = '<button ';
            if (toolbar.class !== '') {
                html += 'class="' + toolbar.class + '" ';
            }
            if (toolbar.method === 'open') {
                html += 'data-open="' + toolbar.url + '" ';
            } else if (toolbar.method === 'batch') {
                html += 'data-href="' + toolbar.url + '" data-batch-all="' + tableId + '" ';
            } else if (toolbar.method === 'href') {
                html +=  'data-href="' + toolbar.url + '" ';
            } else if (toolbar.method === 'none') {
                // 不做任何操作 配合extend使用
            } else {
                html +=  'data-request="' + toolbar.url + '" ';
            }
            if (toolbar.title !== '') {
                html += ' data-title="' + toolbar.title + '" ';
            }
            if (toolbar.method !== 'batch') {
                html += 'data-table="' + tableId + '" ';
            }
            if (toolbar.checkbox) {
                html += (typeof toolbar.checkbox === 'string') ? ' data-checkbox="' + toolbar.checkbox + '" ' : ' data-checkbox="true" ';
            }
            if (toolbar.confirm) {
                html += (typeof toolbar.confirm === 'string') ? ' data-confirm="' + toolbar.confirm + '" ' : ' data-confirm="true" ';
            }
            if (toolbar.sign !== '') {
                html += 'data-sign="' + toolbar.sign + '" ';
            }
            html += toolbar.extend + '>';
            if (toolbar.icon !== '') {
                html += '<i class="' + toolbar.icon + '"></i> ';
            }
            return html + '<span class="layui-hide-xs">'+toolbar.text + '</span></button>\n';
        },
        // 初始化表格列
        colsFormat: function(cols, init) {
            for (let i in cols) {
                var col = cols[i];
                for (let index in col) {
                    var val = col[index];
                    // 判断是否包含初始化数据
                    if (val.init === undefined) {
                        cols[i][index]['init'] = init;
                    }
                    // 格式化列操作栏
                    if (val.templet === aphpTable.formatter.tool && val.operat === undefined) {
                        cols[i][index]['operat'] = ['edit', 'delete'];
                    }
                    // 判断是否包含开关组件
                    if (val.templet === aphpTable.formatter.switch && val.filter === undefined) {
                        cols[i][index]['filter'] = val.field;
                    }
                    // 默认状态字段设置
                    if (val.selectList === undefined && val.field === 'status') {
                        cols[i][index]['selectList'] = {0:'停用',1:'启用'};
                        if (val.search === undefined) {
                            cols[i][index]['search'] = 'select';
                        }
                    }
                    // 判断是否含有搜索下拉列表
                    if (val.selectList !== undefined && val.search === undefined) {
                        cols[i][index]['search'] = 'select';
                    }
                    // 判断是否初始化对齐方式
                    if (val.align === undefined) {
                        cols[i][index]['align'] = 'left';
                    }
                    // 部分字段宽度
                    var sortDefaultFields = ['id', 'sort', 'status', 'title'];
                    if (val.width === undefined && sortDefaultFields.indexOf(val.field) >= 0) {
                        var fw = 50;
                        if (val.field === 'status') {
                            fw = 80;
                        } else if (val.field === 'title') {
                            fw = 120;
                        }
                        cols[i][index]['width'] = fw;
                    }
                    // 初始化图片高度
                    if (val.templet === aphpTable.formatter.image && val.imageHeight === undefined) {
                        cols[i][index]['imageHeight'] = 30;
                    }
                    // 判断是否多层对象
                    if (val.field !== undefined && val.field.split(".").length > 1) {
                        if (val.templet === undefined) {
                            cols[i][index]['templet'] = aphpTable.formatter.value;
                        }
                    }
                }
            }
            return cols;
        },
        // 渲染搜索表单
        renderSearch: function(cols, elem, tableId, searchFormVisible) {
            cols = cols[0] || {};
            var newCols = [];
            var formHtml = '';
            $.each(cols, function(i, d) {
                d.field = d.field || false;
                d.fieldAlias = aphp.getParam(d.fieldAlias, d.field);
                d.title = d.title || d.field || '';
                d.selectList = d.selectList || {};
                d.search = aphp.getParam(d.search, true);
                d.searchTip = d.searchTip || '请输入' + d.title || '';
                d.searchValue = d.searchValue || '';
                d.searchOp = d.searchOp || '=';
                d.timeType = d.timeType || 'datetime';
                d.extend = typeof d.extend === 'undefined' ? '' : d.extend;
                d.addClass = typeof d.addClass === 'undefined' ? (typeof d.addclass === 'undefined' ? 'layui-input' : 'layui-input ' + d.addclass) : 'layui-input ' + d.addClass;
                if (d.field !== false && d.search !== false) {
                    ColumnsForSearch.push(d);
                    switch (d.search) {
                        case true:
                            formHtml += '\t<div class="layui-form-item layui-inline">\n' +
                                '<label class="layui-form-label">' + d.title + '</label>\n' +
                                '<div class="layui-input-inline">\n' +
                                '<input type="hidden" class="operate" name="' + d.fieldAlias + '-operate" data-name="' + d.fieldAlias + '" value="' + d.searchOp + '" readonly>\n' +
                                '<input class="' + d.addClass + '" id="c-' + d.fieldAlias + '" name="' + d.fieldAlias + '" value="' + d.searchValue + '" placeholder="' + d.searchTip + '" ' + d.extend + '>\n' +
                                '</div>\n' +
                                '</div>';
                            break;
                        case 'select':
                            //d.searchOp = '=';
                            var selectHtml = '';
                            $.each(d.selectList, function(sI, sV) {
                                var selected = '';
                                if (sI === d.searchValue) {
                                    selected = 'selected=""';
                                }
                                selectHtml += '<option value="' + sI + '" ' + selected + '>' + sV + '</option>/n';
                            });
                            formHtml += '\t<div class="layui-form-item layui-inline">\n' +
                                '<label class="layui-form-label">' + d.title + '</label>\n' +
                                '<div class="layui-input-inline">\n' +
                                '<input type="hidden" class="operate" name="' + d.fieldAlias + '-operate" data-name="' + d.fieldAlias + '" value="' + d.searchOp + '" readonly>\n' +
                                '<select class="layui-select" id="c-' + d.fieldAlias + '" name="' + d.fieldAlias + '" ' + d.extend + '>\n' +
                                '<option value="">- 全部 -</option> \n' +
                                selectHtml +
                                '</select>\n' +
                                '</div>\n' +
                                '</div>';
                            break;
                        case 'range':
                            d.searchOp = 'range';
                            formHtml += '\t<div class="layui-form-item layui-inline">\n' +
                                '<label class="layui-form-label">' + d.title + '</label>\n' +
                                '<div class="layui-input-inline">\n' +
                                '<input type="hidden" class="operate" name="' + d.fieldAlias + '-operate" data-name="' + d.fieldAlias + '" value="' + d.searchOp + '" readonly>\n' +
                                '<input class="datetime ' + d.addClass + '" data-date-range="-" id="c-' + d.fieldAlias + '" name="' + d.fieldAlias + '" value="' + d.searchValue + '" placeholder="' + d.searchTip + '" ' + d.extend + '>\n' +
                                '</div>\n' +
                                '</div>';
                            break;
                        case 'time':
                            d.searchOp = '=';
                            formHtml += '\t<div class="layui-form-item layui-inline">\n' +
                                '<label class="layui-form-label">' + d.title + '</label>\n' +
                                '<div class="layui-input-inline">\n' +
                                '<input class="datetime ' + d.addClass + '" id="c-' + d.fieldAlias + '" name="' + d.fieldAlias + '"  data-search-op="' + d.searchOp + '"  value="' + d.searchValue + '" placeholder="' + d.searchTip + '" ' + d.extend + '>\n' +
                                '</div>\n' +
                                '</div>';
                            break;
                        case 'between':
                            d.searchOp = 'BETWEEN';
                            formHtml += '\t<div class="layui-form-item layui-inline">\n' +
                                '<input type="hidden" class="operate" name="' + d.fieldAlias + '-operate" data-name="' + d.fieldAlias + '" value="' + d.searchOp + '" readonly>\n' +
                                '<label class="layui-form-label">' + d.title + '</label>\n' +
                                '<div class="layui-input-inline" style="width: 80px;">\n' +
                                '<input type="text" name="' + d.fieldAlias + '" id="' + d.fieldAlias + '-min" placeholder="' + d.searchTip + '" autocomplete="off" class="' + d.addClass + '" ' + d.extend + '>\n' +
                                '</div>\n' +
                                '<div class="layui-form-mid">-</div>\n' +
                                '<div class="layui-input-inline" style="width: 80px;">\n' +
                                '<input type="text" name="' + d.fieldAlias + '" id="' + d.fieldAlias + '-min" placeholder="' + d.searchTip + '" autocomplete="off" class="' + d.addClass + '" ' + d.extend + '>\n' +
                                '</div>\n' +
                                '</div>';
                            break;
                    }
                    //newCols.push(d);
                }
            });
            if (formHtml !== '') {
                $(elem).before('<fieldset style="border:1px solid #ddd;" id="searchFieldset_' + tableId + '" class="table-search-fieldset ' + (searchFormVisible ? "" : "layui-hide") + '">\n' +
                    '<legend>条件搜索</legend>\n' +
                    '<form class="layui-form layui-form-pane form-search form-commonsearch">\n' +
                    formHtml +
                    '<div class="layui-form-item layui-inline" style="margin-left: 115px">\n' +
                    '<button type="submit" class="layui-btn layui-btn-normal" data-type="tableSearch" data-table="' + tableId + '" lay-submit lay-filter="' + tableId + '_filter"> 搜 索</button>\n' +
                    '<button type="reset" class="layui-btn layui-btn-primary" data-table-reset="' + tableId + '"> 重 置 </button>\n' +
                    ' </div>' +
                    '</form>' +
                    '</fieldset>');

                aphpTable.listenSearch(tableId);
                // 初始化form表单
                form.render();
            }
        },
        // 监听搜索
        listenSearch: function(tableId) {
            var that = this;
            that.$commonsearch = $(".table-search-fieldset");
            layui.define(['aphpForm'], function(exports) {
                var aphpForm = layui.aphpForm;
                aphpForm.bindEvent(that.$commonsearch); // 绑定表单事件
            });
            form.on('submit(' + tableId + '_filter)', function(data) {
                var searchQuery = aphpTable.getSearchQuery(that, true);
                table.reload(tableId, {
                    page: { curr: 1 },
                    where: {
                        filter: JSON.stringify(searchQuery.filter),
                        op: JSON.stringify(searchQuery.op)
                    }
                });
                return false;
            })
            //表格点击搜索
            $(document).on("click", ".searchit", function () {
                var value = $(this).data("value");
                var field = $(this).data("field");
                var obj = $("form [name='" + field + "']", that.$commonsearch);
                if (obj.length > 0) {
                    if (obj.is("select")) {
                        $("option[value='" + value + "']", obj).prop("selected", true);
                        form.render('select');
                    } else if (obj.length > 1) {
                        $("form [name='" + field + "'][value='" + value + "']", that.$commonsearch).prop("checked", true);
                    } else {
                        obj.val(value + "");
                    }
                    obj.trigger("change");
                    $("form button[type='submit']",that.$commonsearch).trigger("click");
                }
            });
            //快速搜索
            $(document).on('blur', '#layui-input-search', function(event) {
                var search_field = $(this).data('field');
                var search_value = $(this).val();
                if (search_value === '') {
                    table.reload(tableId, { where: {} });
                    return false;
                }
                // 处理快速搜索
                table.reload(tableId, { where: { search_field: search_field, search_value: search_value } });
                $('#layui-input-search').prop("value", search_value);
                return false
            })
        },
        // 获取搜索请求查询条件
        getSearchQuery: function(that, removeempty) {
            var op = {};
            var filter = {};
            var value = '';
            $("form.form-commonsearch .operate", that.$commonsearch).each(function(i) {
                var name = $(this).data("name");
                var sym = $(this).is("select") ? $("option:selected", this).val() : $(this).val().toUpperCase();
                var obj = $("[name='" + name + "']", that.$commonsearch);
                if (obj.length === 0)
                    return true;
                var vObjCol = ColumnsForSearch[i];
                var process = vObjCol && typeof vObjCol.process == 'function' ? vObjCol.process : null;
                if (obj.length > 1) {
                    if (/BETWEEN$/.test(sym)) {
                        var value_begin = $.trim($("[name='" + name + "']:first", that.$commonsearch).val()),
                            value_end = $.trim($("[name='" + name + "']:last", that.$commonsearch).val());
                        if (value_begin.length || value_end.length) {
                            if (process) {
                                value_begin = process(value_begin, 'begin');
                                value_end = process(value_end, 'end');
                            }
                            value = value_begin + ',' + value_end;
                        } else {
                            value = '';
                        }
                        //如果是时间筛选，将operate置为RANGE
                        if ($("[name='" + name + "']:first", that.$commonsearch).hasClass("datetimepicker")) {
                            sym = 'RANGE';
                        }
                    } else {
                        value = $("[name='" + name + "']:checked", that.$commonsearch).val();
                        value = process ? process(value) : value;
                    }
                } else {
                    value = process ? process(obj.val()) : obj.val();
                }
                if (removeempty && (value === '' || value == null || ($.isArray(value) && value.length === 0)) && !sym.match(/null/i)) {
                    return true;
                }
                op[name] = sym;
                filter[name] = value;
            });
            return { op: op, filter: filter };
        },
        // 监听右侧工具栏 (显示隐藏搜索表单)
        listenToolbar: function(layFilter, tableId) {
            table.on('toolbar(' + layFilter + ')', function(obj) {
                // 搜索表单的显示
                switch (obj.event) {
                    case 'TABLE_SEARCH':
                        var searchFieldsetId = 'searchFieldset_' + tableId;
                        var _that = $("#" + searchFieldsetId);
                        if (_that.hasClass("layui-hide")) {
                            _that.removeClass('layui-hide');
                        } else {
                            _that.addClass('layui-hide');
                        }
                        break;
                }
            });
        },
        // 开关切换渲染
        renderSwitch: function (cols, tableInit, tableId, modifyReload) {
            tableInit.modify_url = tableInit.modify_url || false;
            cols = cols[0] || {};
            tableId = tableId || init.table_render_id;
            if (cols.length > 0) {
                $.each(cols, function (i, v) {
                    v.filter = v.filter || false;
                    if (v.filter !== false && tableInit.modify_url !== false) {
                        aphpTable.listenSwitch({filter: v.filter, url: tableInit.modify_url, tableId: tableId, modifyReload: modifyReload});
                    }
                });
            }
        },
        // 开关切换监听
        listenSwitch: function (option, ok) {
            option.filter = option.filter || '';
            option.url = option.url || '';
            option.field = option.field || option.filter || '';
            option.tableId = option.tableId || init.table_render_id;
            option.modifyReload = option.modifyReload || false;
            form.on('switch(' + option.filter + ')', function (obj) {
                var checked = obj.elem.checked ? 1 : 0;
                if (typeof ok === 'function') {
                    return ok({
                        id: obj.value,
                        checked: checked,
                    });
                } else {
                    var data = {
                        ids: obj.value,
                        param: option.field,
                        value: checked,
                    };
                    // 开关切换
                    var success = option.modifyReload ? function () { table.reload(option.tableId); } : function () {};
                    var error = function () {
                        $(obj.elem).prop('checked', !$(obj.elem).prop('checked'));
                        form.render();
                    }
                    aphp.request.post(option.url, data, 0, success, error);
                }
            });
        },
        // 监听字段编辑事件
        listenFieldEdit: function(tableInit, layFilter, tableId, modifyReload) {
            tableInit.modify_url = tableInit.modify_url || false;
            tableId = tableId || init.table_render_id;
            if (tableInit.modify_url !== false) {
                table.on('edit(' + layFilter + ')', function(obj) {
                    var value = obj.value,
                        data = obj.data,
                        id = data.id,
                        field = obj.field;
                    var _data = {
                        ids: id,
                        param: field,
                        value: value,
                    };
                    // 编辑单元格
                    var success = modifyReload ? function () { table.reload(tableId); } : function () {};
                    aphp.request.post(tableInit.modify_url, _data, 0, success, function () { table.reload(tableId); });
                });
            }
        },
        // 字段格式化显示模板
        formatter: {
            // 行操作按钮显示
            tool: function(data) {
                var that = this;
                that.operat = that.operat || ['edit', 'delete'];
                var elem = that.init.table_elem || init.table_elem;
                var html = '';
                $.each(that.operat, function(i, item) {
                    if (typeof item === 'string') {
                        switch (item) {
                            case 'edit':
                                var operat = {
                                    title: '编辑',
                                    text: "",
                                    class: 'layui-btn layui-btn-normal layui-btn-sm',
                                    icon: 'layui-icon layui-icon-edit',
                                    method: 'open',
                                    url: that.init.edit_url,
                                    auth: 'edit',
                                };
                                operat.url = aphpTable.rowBarUrl(operat, data);
                                if (aphp.checkAuth(operat.auth, elem)) {
                                    html += aphpTable.rowBarBuild(operat);
                                }
                                break;
                            case 'delete':
                                var operat = {
                                    title: '删除',
                                    text: "",
                                    class: 'layui-btn layui-btn-danger layui-btn-sm layui-tr-del',
                                    icon: 'layui-icon layui-icon-delete',
                                    method: 'href',
                                    url: that.init.delete_url,
                                    auth: 'delete',
                                    field_name: 'ids',
                                    extend: ' data-table="'+that.init.table_render_id+'"',
                                };
                                operat.url = aphpTable.rowBarUrl(operat, data);
                                if (aphp.checkAuth(operat.auth, elem)) {
                                    html += aphpTable.rowBarBuild(operat);
                                }
                                break;
                        }

                    } else if (typeof item === 'object') {
                        // 自定义按钮
                        $.each(item, function(i, operat) {
                            let hidden = typeof operat.hidden === 'function' ? operat.hidden.call(aphpTable, data, operat) : (typeof operat.hidden !== 'undefined' ? operat.hidden : false);
                            if (hidden) {
                                return true;
                            }
                            let url = operat.url || '';
                            operat.data_id = data.id;
                            operat.class = operat.class || '';
                            operat.icon = operat.icon || '';
                            operat.auth = operat.auth || '';
                            operat.method = operat.method || 'open';
                            operat.field = operat.field || 'id';
                            operat.text = typeof operat.text === 'function' ? operat.text.call(aphpTable, data, operat) : operat.text ? operat.text : '';
                            operat.title = typeof operat.title === 'function' ? operat.title.call(aphpTable, data, operat) : operat.title ? operat.title : operat.text;
                            operat.extend = operat.extend || '';
                            operat.url = typeof url === 'function' ? url.call(aphpTable, data, operat) : (url ? aphpTable.rowBarUrl(operat, data) : 'javascript:;');
                            let disable = typeof operat.disable === 'function' ? operat.disable.call(aphpTable, data, operat) : (typeof operat.disable !== 'undefined' ? operat.disable : false);
                            if (disable) {
                                operat.class = operat.class + ' layui-btn-disabled';
                            }
                            if (aphp.checkAuth(operat.auth, elem)) {
                                html += aphpTable.rowBarBuild(operat);
                            }
                        });
                    }
                });
                return html;
            },
            // 行状态显示
            status: function (data) {
                var custom = {normal: 'success', hidden: 'gray', deleted: 'danger', locked: 'info'};
                if (typeof this.custom !== 'undefined') {
                    custom = $.extend(custom, this.custom);
                }
                this.custom = custom;
                this.icon = 'layui-icon layui-icon-circle-dot';
                return aphpTable.formatter.normal.call(this, data);
            },
            // 行文字样式
            normal: function (data) {
                var that = this;
                var colorArr = ["danger", "success", "primary", "warning", "info", "gray", "red", "yellow", "aqua", "blue", "navy", "teal", "olive", "lime", "fuchsia", "purple", "maroon"];
                var custom = {};
                if (typeof that.custom !== 'undefined') {
                    custom = $.extend(custom, that.custom);
                }
                var field = that.field;
                try {
                    var value = aphpTable.getItemField(data,field);
                    value = value == null || value.length === 0 ? '' : value.toString();
                } catch (e) {
                    var value = undefined;
                }
                value = value == null || value.length === 0 ? '' : value.toString();
                var keys = typeof that.selectList === 'object' ? Object.keys(that.selectList) : [];
                var index = keys.indexOf(value);
                var color = value && typeof custom[value] !== 'undefined' ? custom[value] : null;
                var display = index > -1 ? that.selectList[value] : null;
                var icon = typeof that.icon !== 'undefined' ? that.icon : null;
                if (!color) {
                    color = index > -1 && typeof colorArr[index] !== 'undefined' ? colorArr[index] : 'primary';
                }
                if (!display) {
                    display = value.charAt(0).toUpperCase() + value.slice(1);
                }
                var html = '<span class="text-' + color + '">' + (icon ? '<i class="' + icon + '"></i>' : '') + display + '</span>';
                if (that.search !== false) {
                    html = '<a href="javascript:;" class="searchit" lay-tips="点击搜索 ' + display + '" data-field="' + this.field + '" data-value="' + value + '">' + html + '</a>';
                }
                return html;
            },
            // 行属性信息
            flag: function (data) {
                var that = this;
                var field = that.field;
                try {
                    var value = aphpTable.getItemField(data,field);
                    value = value == null || value.length === 0 ? '' : value.toString();
                } catch (e) {
                    var value = undefined;
                }
                //赤色 墨绿 蓝色 藏青 雅黑 橙色
                var colorArr = {0:'red',1:'green',2:'blue',3:'cyan',4:'black',5:'orange'};
                //如果字段列有定义custom
                if (typeof that.custom !== 'undefined') {
                    colorArr = $.extend(colorArr, that.custom);
                }
                if (typeof that.selectList === 'object' && typeof that.custom === 'undefined') {
                    var i = 0;
                    var searchValues = Object.values(colorArr);
                    $.each(that.selectList, function (key, val) {
                        if (typeof colorArr[key] == 'undefined') {
                            colorArr[key] = searchValues[i];
                            i = typeof searchValues[i + 1] === 'undefined' ? 0 : i + 1;
                        }
                    });
                }
                //渲染Flag
                var html = [];
                var arr = value !== '' ? value.split(',') : [];
                var color, display, label;
                $.each(arr, function (i, value) {
                    value = value == null || value.length === 0 ? '' : value.toString();
                    if (value === '')
                        return true;
                    color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'green';
                    display = typeof that.selectList !== 'undefined' && typeof that.selectList[value] !== 'undefined' ? that.selectList[value] : value.charAt(0).toUpperCase() + value.slice(1);
                    label = '<span class="layui-badge layui-bg-' + color + '">' + display + '</span>';
                    if (that.search !== false) {
                        html.push('<a href="javascript:;" class="searchit" lay-tips="点击搜索 ' + display + '" data-field="' + field + '" data-value="' + value + '">' + label + '</a>');
                    } else {
                        html.push(label);
                    }
                })
                return html.join(' ');
            },
            // 行标签显示
            label: function (data) {
                return aphpTable.formatter.flag.call(this, data);
            },
            // 状态切换
            switch: function (data) {
                var that = this;
                var elem = that.init.table_elem || init.table_elem;
                // 如果没有权限则显示status
                if (!aphp.checkAuth('modify', elem)) {
                    return aphpTable.formatter.status.call(this, data);
                }
                var field = that.field;
                that.filter = that.filter || that.field || null;
                that.checked = that.checked || 1;
                that.tips = that.tips || '启用|停用';
                try {
                    var value = aphpTable.getItemField(data,field);
                } catch (e) {
                    var value = undefined;
                }
                var checked = value === that.checked ? 'checked' : '';
                return laytpl('<input type="checkbox" name="' + that.field + '" value="' + data.id + '" lay-skin="switch" lay-text="' + that.tips + '" lay-filter="' + that.filter + '" ' + checked + ' >').render(data);
            },
            // 单图显示
            image: function(data) {
                var that = this;
                that.imageWidth = that.imageWidth || 80;
                that.imageHeight = that.imageHeight || 30;
                that.imageSplit = that.imageSplit || ',';
                that.imageJoin = that.imageJoin || ' ';
                that.title = that.title || that.field;
                var field = that.field,
                    title = data[that.title] || that.title;
                try {
                    var value = aphpTable.getItemField(data,field);
                } catch (e) {
                    var value = undefined;
                }
                if (!value) {
                    return '';
                } else {
                    var valuesHtml = [];
                    valuesHtml.push('<img style="max-width: ' + that.imageWidth + 'px; max-height: ' + that.imageHeight + 'px;" src="' + value + '" data-image="' + title + '">');
                    return valuesHtml.join(that.imageJoin);
                }
            },
            // 多图显示
            images: function (data) {
                var that = this;
                that.imageWidth = that.imageWidth || 80;
                that.imageHeight = that.imageHeight || 30;
                that.imageSplit = that.imageSplit || ',';
                that.imageJoin = that.imageJoin || ' ';
                that.title = that.title || that.field;
                var field = that.field,
                    title = data[that.title];
                try {
                    var value = aphpTable.getItemField(data,field);
                } catch (e) {
                    var value = undefined;
                }
                if (!value) {
                    return '';
                } else {
                    var values = value.split(that.imageSplit),
                        valuesHtml = [];
                    values.forEach((value, index) => {
                        valuesHtml.push('<img style="max-width: ' + that.imageWidth + 'px; max-height: ' + that.imageHeight + 'px;" src="' + value + '" data-image="' + title + '">');
                    });
                    return valuesHtml.join(that.imageJoin);
                }
            },
            // 单文件类型图标
            file: function(data) {
                var that = this;
                that.imageWidth = that.imageWidth || 80;
                that.imageHeight = that.imageHeight || 30;
                that.imageSplit = that.imageSplit || ',';
                that.imageJoin = that.imageJoin || ' ';
                that.title = that.title || that.field;
                var field = that.field,
                    title = data[that.title];
                try {
                    var value = aphpTable.getItemField(data,field);
                } catch (e) {
                    var value = undefined;
                }
                if (!value) {
                    return '';
                } else {
                    var values = value.split(that.imageSplit),
                        valuesHtml = [];
                    values.forEach((value, index) => {
                        let suffix = /[\.]?([a-zA-Z0-9]+)$/.exec(value);
                        suffix = suffix ? suffix[1] : 'file';
                        let url = 'http://api.aphp.top/image/icon.html?suffix='+ suffix; // aphp.fixUrl("api/icon?suffix=" + suffix); // 获取文件图标
                        valuesHtml.push('<img alt="suffix" style="max-width: ' + that.imageWidth + 'px; max-height: ' + that.imageHeight + 'px;" src="' + url + '">');
                    });
                    return valuesHtml.join(that.imageJoin);
                }
            },
            // 多文件类型图标
            files: function (data) {
                return aphpTable.formatter.image.file(this, data);
            },
            // url地址
            url: function(data) {
                var field = this.field;
                //var host = window.location.protocol + '//' + window.location.host;
                try {
                    var value = aphpTable.getItemField(data,field);
                } catch (e) {
                    var value = undefined;
                }
                if (!value) {
                    return '-'; // <span class="copy" data-copy-text="' + host + value + '"><i class="layui-icon layui-icon-file-b"></i></span>
                }
                return '<a class="layui-btn layui-btn-primary layui-btn-xs" href="' + value + '" target="_blank"><i class="layui-icon layui-icon-link"></i></a>';
            },
            // 价格
            price: function(data) {
                var field = this.field;
                try {
                    var value = aphpTable.getItemField(data,field);
                } catch (e) {
                    var value = undefined;
                }
                return '<span>￥' + value + '</span>';
            },
            // 图标
            icon: function(data) {
                var field = this.field;
                try {
                    var value = aphpTable.getItemField(data,field);
                } catch (e) {
                    var value = undefined;
                }
                return '<i class="' + value + '"></i>';
            },
            // 文本
            text: function(data) {
                var field = this.field;
                try {
                    var value = aphpTable.getItemField(data,field);
                } catch (e) {
                    var value = undefined;
                }
                return '<span class="line-limit-length">' + value + '</span>';
            },
            // 值
            value: function(data) {
                var field = this.field;
                try {
                    var value = aphpTable.getItemField(data,field);
                } catch (e) {
                    var value = undefined;
                }
                return '<span>' + value + '</span>';
            },
            // 日期时间
            datetime: function (data) {
                var that = this;
                var field = that.field;
                try {
                    var value = aphpTable.getItemField(data,field);
                } catch (e) {
                    var value = undefined;
                }
                var datetimeFormat = typeof that.datetimeFormat === 'undefined' ? 'yyyy-MM-dd HH:mm:ss' : that.datetimeFormat;
                if (value && isNaN(Date.parse(value))) {
                    return layui.util.toDateString(value * 1000, datetimeFormat)
                } else if (value && !isNaN(Date.parse(value))) {
                    return layui.util.toDateString(Date.parse(value), datetimeFormat)
                } else {
                    return '-';
                }
            }
        },
        // 获取对象属性值
        getItemField: function (item, field) {
            var value = item;
            if (typeof field !== 'string' || item.hasOwnProperty(field)) {
                return item[field];
            }
            var props = field.split('.');
            for (var p in props) {
                if (props.hasOwnProperty(p)) {
                    value = value && value[props[p]];
                }
            }
            return value;
        },
        // 行操作栏url处理
        rowBarUrl(operat, data) {
            var url = operat.url || '';
            var field_name = operat.field_name || 'id';
            var ids = data.id || '0';
            var at = (url.indexOf("?") === -1) ? '?' : '&';
            return url + at + field_name + '=' + ids;
        },
        // 生成行操作按钮
        rowBarBuild: function(operat) {
            operat.title = operat.title || ''; // 标题必须
            operat.text = operat.text || ''; // 显示文字
            operat.class = operat.class || ''; // 样式
            operat.icon = operat.icon || ''; // 图标
            operat.url = operat.url || ''; // url
            operat.method = operat.method || 'open'; //open, request, none
            operat.extend = operat.extend || ''; //扩展属性
            operat.data_id = operat.data_id || ''; //操作行ID
            operat.confirm = operat.confirm || false; //操作确认
            var html = '<a ';
            if (operat.class !== '') {
                html += 'class="' + operat.class + '" ';
            }
            if (operat.method === 'open') {
                html += 'data-open="' + operat.url + '" ';
            } else if (operat.method === 'href'){
                html += 'href="' + operat.url + '" ';
            } else if (operat.method === 'none'){
                // 常用于与extend配合，自定义监听按钮
                html += (operat.url !== '') ? 'data-href="' + operat.url + '" ' : 'href="javascript:;" ';
            } else {
                html += 'data-request="' + operat.url + '" ';
            }
            if (operat.method !== 'none' && operat.title !== '') {
                html += 'data-title="' + operat.title + '" ';
            }
            if (operat.confirm) {
                html += (typeof operat.confirm === 'string') ? ' data-confirm="' + operat.confirm + '" ' : ' data-confirm="true" ';
            }
            if (operat.method === 'none' && operat.data_id !== '') {
                html += 'data-id="' + operat.data_id + '" ';
            }
            html += operat.extend + '>';
            if (operat.icon !== '') {
                html += '<i class="' + operat.icon + '"></i> ';
            }
            return html + operat.text + '</a>';
        },
    };

    exports(MOD_NAME, aphpTable);
});